/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jmooc.soap;

import com.jmooc.entity.User;
import com.jmooc.service.UserService;
import java.util.Date;
import javax.ejb.EJB;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;

/**
 *
 * @author Group
 */
@WebService(serviceName = "soap/users")
public class UserWebService {
    @EJB
    private UserService userService;

    @WebMethod(operationName = "getById")
    public User getById(@WebParam(name = "token") String token, @WebParam(name = "id") Long id) {
        // vérifie le token
        User user = userService.getById(id);
        
        if (userService.isTokenValid(user, token)) {
            return user;
        }
        
        return null;
    }

    @WebMethod(operationName = "login")
    public String login(@WebParam(name = "email") String login, @WebParam(name = "password") String password) {
        if (userService.canLogin(login, password)) {
            String token = userService.generateToken();
            Date expire = new Date();
            expire.setTime(expire.getTime() + 60 * 60 * 24);
            
            User user = userService.getByEmail(login);
            user.setToken(token);
            user.setTokenExpiration(new Date());
            
            userService.update(user);
            
            return token;
        }
        else {
            return "Error";
        }
    }
    
}
